package cc.rengu.redp.common.utils;

import cc.rengu.redp.common.utils.gmhelper.SM3Util;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

public class HashUtil {

    protected HashUtil() {

    }

    private static final String ALGORITH_NAME = "md5";

    private static final int HASH_ITERATIONS = 2;

    public static String encrypt(String password) {
        return new SimpleHash(ALGORITH_NAME, password, ByteSource.Util.bytes(password), HASH_ITERATIONS).toHex();
    }

    public static String encrypt(String username, String password) {
        return new SimpleHash(ALGORITH_NAME, password, ByteSource.Util.bytes(username.toLowerCase() + password),
                HASH_ITERATIONS).toHex();
    }

    /**
     * 国密算法的用户和密码散列保存，并加入特殊的加盐规则
     * @param username
     * @param password
     * @return
     */
    public static String encryptGm(String username, String password) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < username.length(); i++) {
            sb.append(username.charAt(i));
            if (i < password.length()) {
                sb.append(password.charAt(i));
            } else {
                continue;
            }
        }
        sb.append(password);
        return EncryptUtil.byteArr2HexStr(SM3Util.hash(sb.toString().getBytes()));
    }
}
